<template>
    <div class="playing-song-detail" ref="playingSongDetail">
        <!-- 返回顶部按钮 -->
        <el-backtop target=".playing-song-detail" :right="20" :bottom="75"></el-backtop>
        <span class="iconfont icon-xiangxiajiantou" @click="closeSongDetail"></span>
        <!-- 主要内容 -->
        <div class="main-content" v-if="Object.keys(music.nowSongDetail).length !== 0">
            <!-- 顶部 -->
            <div class="top-lyrics">
                <!-- 左边旋转唱片 -->
                <div class="left-cover">
                    <!-- 唱片开关 -->
                    <div class="switchs swichsRotate"
                        :class="{ switchsPlay: music.isplaying, switchsPause: !music.isplaying }">
                        <img src="@/assets/images/cp1.png" alt="">
                    </div>
                    <!-- 唱片旋转 -->
                    <div class="record recordRotate" :class="{ startRotate: music.isplaying }" @click="changePlay">
                        <img class="cp2" src="@/assets/images/cp2.png" alt="">
                        <img class="cover" :src="cover" alt="" />
                    </div>
                    <img :src="cover" alt="" class="song-bgImg">
                </div>
                <!-- 右边歌词 -->
                <div class="right-lyrics">
                    <!-- 标题 -->
                    <div class="title">
                        <h2>{{ music.nowSongDetail.name }}</h2>
                        <i class="iconfont icon-vip" v-if="music.nowSongDetail.fee == 1"></i>
                        <i class="iconfont icon-MV" style="cursor: pointer;" v-if="music.nowSongDetail.mv != 0"
                            @click="gotoMV"></i>
                    </div>
                    <div class="name">
                        歌手：<span @click="gotoSinger"> {{ music.nowSongDetail.ar[0].name }}</span>
                        专辑：<span @click="gotoAlbum">{{ music.nowSongDetail.al.name }}</span>
                    </div>
                    <!-- 歌词滚动区域 -->
                    <div class="scrollLyric" ref="scrollLyric">
                        <ul v-if="info.formatlyric.length !== 0">
                            <li v-for="(item, index) in info.formatlyric" :key="index"
                                :class="{ currentLyric: index === music.currentRow }" @mouseover="showTime(index)"
                                @mouseleave="info.isActive = false">
                                <span class="time" v-show="info.isActive && info.currentIndex === index">{{
                                    instance.proxy.$formatDuration.formatDurations(item.time) }}
                                </span>
                                <span class="lyric-item">{{ item.text.trim() }}</span>
                                <span class="playIcon" @click="lyricClick(item)">
                                    <i class="iconfont icon-bofang"
                                        v-show="info.isActive && info.currentIndex === index"></i>
                                </span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="bottom-content">
                <div class="song-comment">
                    <CommentPage :commentType="0" :commentresId="music.nowSongDetail.id"></CommentPage>
                </div>
            </div>
        </div>
        <div class="nosongdetail" v-if="Object.keys(music.nowSongDetail).length == 0">
            <div>暂无音乐</div>
        </div>
    </div>
</template>

<script setup>
import 'animate.css';
import { reactive, onMounted, computed, getCurrentInstance, watch } from 'vue'
import { getNowLyric } from '@/api/playmusic/playmusic.js'
import { useMusicStore } from '@/store/music.js'
import { useRouter } from 'vue-router'
import CommentPage from '../comment/CommentPage.vue';
// import mitter from '@/utils/mitt.js'

const music = useMusicStore()
const instance = getCurrentInstance()
const router = useRouter()
const info = reactive({
    songId: '',  //歌曲id
    formatlyric: [],  //格式化后的歌词
    currentIndex: null,  //当前鼠标经过的歌词索引
    isActive: false, //鼠标是否经过歌词
})


//关闭当前歌曲详细页
function closeSongDetail() {
    music.isShowSongDetail = !music.isShowSongDetail
}

//获取当前播放歌曲歌词
async function getNowLyricBy(songId) {
    let res = await getNowLyric(songId)
    if (res.data.code === 200) {
        let lyric = res.data.lrc.lyric
        formatlyricBy(lyric)
        //保存到仓库中
        music.saveCurrentLyric(info.formatlyric)
    }
}

// mitter.on('changeNowLyric',getNowLyricBy)

//格式化歌词  
/**
 * 先把字符串根据 '\n'分割成每行字符串数组
 * 在获取每行歌词时，将其分割成时间和歌词
 * 先保存歌词，然后再分割 ':' 时间字符串 分割成分和秒
 * 然后把分和秒 转换成秒，用于与仓库中实时秒数做对比，便于实现滚动歌词
 * 最后插入到歌词对象中保存
 */
function formatlyricBy(lyric) {
    let lyric_arr = lyric.split('\n'); //得到每行歌词字符串数组
    let length = lyric_arr.length
    for (let i = 0; i < length; i++) {
        let lyric_row = lyric_arr[i]  //获取每行歌曲
        let lyric_row_arr = lyric_row.split(']')  //分割成时间和歌词数组
        let lyric_row_text = lyric_row_arr.pop()  //利用pop方法获取歌词，最后一项
        //处理歌词时间
        lyric_row_arr.forEach(item => {
            let LyricRowObj = {}  //新创一个歌词对象
            let time_arr = item.substring(1).split(':')  //提取出每行的时间 分钟与分秒隔开
            //把时间转换成秒  row_second === currentSecond 跟这个做对比
            let row_second = time_arr[0] * 60 + Math.ceil(time_arr[1])
            if (lyric_row_text.trim().length !== 0) {  //如果歌词不为空
                LyricRowObj.time = row_second
                LyricRowObj.text = lyric_row_text
                info.formatlyric.push(LyricRowObj)  //再放入格式化数组中
            }
        });
    }
    //根据时间对歌词排序
    info.formatlyric.sort((a, b) => {
        return a.time - b.time
    })

}

//显示时间
function showTime(index) {
    info.currentIndex = index
    info.isActive = true
}

//点击歌词
function lyricClick(item, index) {
    //获取音频标签
    let audio = document.querySelector('#audio')
    audio.currentTime = item.time //赋予当前歌词的时间  跳转到这个时间播放
    info.isActive = false
}

//点击唱片开始播放
function startPlay() {
    music.changePlayState(true)
    document.querySelector('#audio').play()
}
//点击唱片取消播放
function pausePlay() {
    music.changePlayState(false)
    document.querySelector('#audio').pause()
}

//点击唱片控制是否播放
function changePlay() {
    if (music.isplaying) pausePlay()
    else startPlay()
}


//前往歌手页
function gotoSinger() {
    router.push("/singerdetail/" + music.nowSongDetail.ar[0].id)
    closeSongDetail()
}
//前往专辑页
function gotoAlbum() {
    router.push("/albumdetail/" + music.nowSongDetail.al.id)
    closeSongDetail()
}
//前往mv页
function gotoMV() {
    router.push({
        name: 'Videodetail',
        params: { id: music.nowSongDetail.mv, type: 'mv' }
    })
    closeSongDetail()
}

const cover = computed(() => {
    return music.nowSongDetail.al.picUrl
})

//监听实时秒数的变化  实现歌词滚动
watch(() => music.currentSecond, () => {
    if (music.currentSecond !== 0) {
        //遍历歌词数组
        info.formatlyric.forEach((item, index) => {
            //如果实时秒数等于某一个歌词对应的秒数
            if (Math.ceil(music.currentSecond) == item.time) {
                music.saveCurrentRow(index);  //保存当前行
                if (!info.isActive) {  //鼠标在歌词上面停止移动
                    //滚动歌词  有点小bug，因为index每次会增加，所以滚动top会一直增加
                    instance.refs.scrollLyric.scrollTo({
                        top: 40 * index,
                        behavior: 'smooth'
                    })

                }
            }
        })
    }
})
//监听当前歌曲的变化
watch(() => music.nowSongDetail, () => {
    if (Object.keys(music.nowSongDetail).length !== 0) {
        info.formatlyric = []  //清空歌词数组
        getNowLyricBy(music.nowSongDetail.id)
        music.saveCurrentRow(0)  //清空当前播放的行数
    }
})

//当打开详细页的时候，立即滚动到当前播放行   监听不到？？？ 很奇怪
watch(() => music.isShowSongDetail, () => {
    if (music.isShowSongDetail && Object.keys(music.nowSongDetail).length !== 0) {
        instance.refs.scrollLyric.scrollTop = 40 * music.currentRow
        instance.refs.playingSongDetail.scrollTop = 0
    }
})

onMounted(() => {
    info.songId = music.nowSongDetail.id
    getNowLyricBy(info.songId)
})

</script>

<style lang="scss" scoped>
.playing-song-detail {
    position: absolute;
    bottom: 70px;
    left: 0;
    right: 0;
    width: 100%;
    height: calc(100vh - 70px);
    background: #fff;
    z-index: 99; //覆盖住底层东西
    overflow-y: scroll;

    .icon-xiangxiajiantou {
        font-size: 32px;
        position: fixed;
        top: 10px;
        left: 20px;
        font-weight: 700;
        cursor: pointer;
    }

    .main-content {
        position: relative;
        width: 1350px;
        height: 100%;
        margin: 0 auto;

        .top-lyrics {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 500px;
            width: 70%;
            margin: 0px auto;

            .left-cover {
                position: relative;
                height: 100%;
                width: 30%;
                display: flex;
                justify-content: center;
                align-items: center;

                .song-bgImg {
                    position: absolute;
                    top: 50%;
                    left: -90%;
                    z-index: -1;
                    width: 300%;
                    border-radius: 20%;
                    transform: translate(20%,-50%); //移动自身宽度高度的 20 50 
                    filter: blur(350px);   //滤镜  blur 设置高斯模糊
                }

                .switchs {
                    position: absolute;
                    left: 50%;
                    top: 8%;
                    width: 40%;
                    z-index: 2; //确保开关不被覆盖
                    transform-origin: 0 0; //设置旋转元素的基点位置

                    img {
                        width: 100%;
                    }
                }

                .record {
                    position: relative;
                    width: 100%;

                    .cp2 {
                        width: 100%;
                    }

                    .cover {
                        position: absolute;
                        top: 40px;
                        left: 45px;
                        border-radius: 50%;
                        width: 70%;
                        z-index: -1; //确保图片在最底层
                    }
                }
            }

            .right-lyrics {
                margin-left: 20px;
                width: 60%;


                .title {
                    height: 50px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }

                .name {
                    text-align: center;
                    color: #7f7f7f;

                    span {
                        margin-right: 15px;
                        font-size: 10px;
                        color: #7f7f7f;

                        &:hover {
                            color: #fd544e;
                            cursor: pointer;
                        }
                    }
                }

                .scrollLyric {
                    margin-top: 20px;
                    height: 315px;
                    text-align: center;
                    overflow-y: auto;

                    /*浏览器决定是否可见*/
                    ul {
                        padding: 135px 0;

                        li {
                            position: relative;
                            transition: all 0.3s ease-in;

                            &:hover {
                                cursor: pointer;
                            }

                            .time {
                                position: absolute;
                                left: 100px;
                                top: 22px;
                                color: #7f7f7f;
                                display: inline-block;
                                font-size: 10px;
                            }

                            .lyric-item {
                                color: #7f7f7f;
                                display: inline-block;
                                margin-top: 20px;
                            }

                            .playIcon {
                                .icon-bofang {
                                    position: absolute;
                                    font-size: 13px;
                                    right: 10px;
                                    bottom: 3px;
                                }
                            }
                        }
                    }
                }

                ::-webkit-scrollbar {
                    //修改滚动条样式  
                    width: 0px; //宽度为0
                }
            }
        }

        .bottom-content {
            margin: 15px auto;
            width: 50%;

            .song-comment {
                padding-bottom: 15px;
            }
        }
    }

    .nosongdetail {
        display: flex;
        height: 100%;
        justify-content: center;
        align-items: center;
        font-size: 24px;
        font-weight: 700;
    }
}

.icon-vip,
.icon-MV {
    margin-left: 5px;
    color: #fd544e;
}

.currentLyric {
    font-size: 18px;
    font-weight: 700;
}

//唱片开关旋转动画
.swichsRotate {
    //一开始停止动画
    animation-play-state: paused;
}

.switchsPlay,
.switchsPause {
    //定义动画
    animation-duration: 0.35s;
    animation-timing-function: linear;
    animation-play-state: running;
    animation-fill-mode: forwards; //保持移动之后的位置
}

//播放的播放开关的类
.switchsPlay {
    //使用动画
    animation-name: switchsPlay;
}

//停止播放的播放开关的类
.switchsPause {
    //使用动画
    animation-name: switchsPause;
}


//定义动画  switchsPlay  开关开
@keyframes switchsPlay {
    0% {
        transform: rotate(-8deg);
    }

    100% {
        transform: rotate(20deg);
    }
}

//开关 关
@keyframes switchsPause {
    0% {
        transform: rotate(20deg);
    }

    100% {
        transform: rotate(-8deg);
    }
}

//定义唱片相关动画
.recordRotate {
    animation-name: recordRotate;
    animation-play-state: paused;
    animation-duration: 20s;
    animation-timing-function: linear; //平滑旋转
    animation-iteration-count: infinite; //无限循环动画
}

//定义唱片旋转
.startRotate {
    animation-play-state: running;
}

//定义唱片旋转
@keyframes recordRotate {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>